package com.hoshiibuy.fileServer.service.impl;

import java.io.InputStream;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.hoshiibuy.fileServer.config.ObsClientSingleton;
import com.hoshiibuy.fileServer.result.Result;
import com.hoshiibuy.fileServer.service.FileObjectService;
import com.hoshiibuy.fileServer.util.ObsUtil;
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.DeleteObjectResult;
import com.obs.services.model.PutObjectResult;

/**
 * 华为云obs文件对象操作服务接口类实现
 * 
 * @author Mr.wu
 *
 */
@Service
public class ObsFileObjectServiceImpl implements FileObjectService {

	private final static Logger logger = LoggerFactory.getLogger(ObsFileObjectServiceImpl.class);

	@Override
	public Result<String> uploadFile(String bucketName, String folder, String objectKey, InputStream fileStream)
			throws Exception {
		try {
			ObsClient obsClient = ObsClientSingleton.getInstance();
			boolean exists = ObsUtil.bucketIsExists(bucketName);
			if (!exists) {
				return Result.wrap404Error("存储空间不存在");
			}
			PutObjectResult result = null;
			if (StringUtils.isNotBlank(folder)) {
				// 创建文件夹
				result = obsClient.putObject(bucketName, folder, fileStream);
				result = obsClient.putObject(bucketName, folder + objectKey, fileStream);
			} else {
				result = obsClient.putObject(bucketName, objectKey, fileStream);
			}

			return Result.wrapSuccess(result.getObjectUrl());
		} catch (ObsException e) {
			// TODO: handle exception
			logger.error("上传失败，华为云服务出错：", e);
			return Result.wrap500Error("上传失败,华为云obs服务出错");
		} catch (Exception e) {
			logger.error("上传失败：", e);
			return Result.wrap500Error("上传失败");
			// TODO: handle exception
		}

	}

	@Override
	public Result<String> test() {
		return Result.wrap404Error("存储空间不存在");
	}

	@Override
	public Result<String> deleteFile(String bucketName, String objectKey) {
		// TODO Auto-generated method stub
		try {
			ObsClient obsClient = ObsClientSingleton.getInstance();
			boolean exists = ObsUtil.bucketIsExists(bucketName);
			if (!exists) {
				return Result.wrap404Error("存储空间不存在");
			}
			DeleteObjectResult result = null;
			result = obsClient.deleteObject(bucketName, objectKey);

			return Result.wrapSuccess();
		} catch (ObsException e) {
			logger.error("上传失败，华为云服务出错：", e);
			return Result.wrap500Error("上传失败,华为云obs服务出错");
		} catch (Exception e) {
			logger.error("上传失败：", e);
			return Result.wrap500Error("上传失败");
		}
	}

}
